﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text.RegularExpressions;

namespace Joe.Coin.Monitor.App
{
    public static class WebReq
    {
        public static T GetByUrl<T>(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = WebRequestMethods.Http.Get;
            request.ContentType = "application/json; charset=utf-8";
            request.Accept = "application/json";
            request.Timeout = 15000;//6秒
            string rspStr;
            var response = (HttpWebResponse)request.GetResponse();

            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                rspStr = sr.ReadToEnd();
            }

            rspStr = rspStr.Replace("vol_cny", "cny_vol");

            Regex rgx = new Regex("\"vol_[a-zA-Z0-9]{1,5}\"");

            MatchCollection mc = rgx.Matches(rspStr);
            foreach (Match i in mc) {
                rspStr = rspStr.Replace(i.Value, "\"coin_vol\"");
            }


            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
             using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(rspStr)))
             {
                 var obj = (T)serializer.ReadObject(ms);
                 return obj;
             }
        }
    }
}
